<template>
    <div style="min-height: calc(100vh - 40px);width: 1093px;margin: 0 auto;background-color: #fff;padding: 20px;">
        <div class="button-container">
            <el-button type="primary" icon="el-icon-back" @click="goBock">返回</el-button>
            <span>
                <el-button type="" icon="el-icon-plus" v-if="!isView" @click="addItem">新增异动项</el-button>
                <el-button type="success" icon="el-icon-check" v-if="!isView" @click="saveData">保存</el-button>
                <el-button type="primary" icon="el-icon-menu" @click="goToList">列表</el-button>
                <!-- <button @click="printToPDF">打印PDF</button> -->
                <el-button type="danger" icon="el-icon-delete" v-if="!isView" @click="deleteSelected">删除选中</el-button>

                <el-button type="primary" icon="el-icon-printer" @click="printForm">打印</el-button>
            </span>
            <!-- <button @click="goBack">返回</button>
            <span>
                <button v-if="!isView" @click="addItem">新增行</button>
                <button v-if="!isView" @click="saveData">保存</button>
                <button @click="goToList">列表</button>
                <button v-if="!isView" @click="deleteSelected">删除选中</button>
                <button @click="printToPDF">打印pdf</button>
            </span> -->
        </div>
        <div id="format-table">
            <h2 style="margin: 15px 0px;">发电费用核算表</h2>
            <table border="1" style="text-align: center;">
                <thead>
                    <tr>
                        <th class="checkbox" v-if="!isView"><input type="checkbox" v-model="isAllSelected"
                                @change="toggleSelectAll">
                        </th>
                        <th>序号</th>
                        <th>负荷</th>
                        <th>每小时费用</th>
                        <th>每度电费用</th>
                        <th>每月发电度数</th>
                        <th>每月发电费用</th>
                        <th>备注</th>
                    </tr>
                </thead>
                <tbody>
                    <tr v-for="(item, index) in powerCostList" :key="index">
                        <td class="checkbox" v-if="!isView"><input type="checkbox" v-model="selectedIndices"
                                :value="index"></td>
                        <td>{{ index + 1 }}</td>
                        <td>
                            <input v-if="!isView" v-model="item.loadName">
                            <span v-else>{{ item.loadName }}</span>
                        </td>
                        <td>
                            <input v-if="!isView" v-model="item.hourlyCost">
                            <span v-else>{{ item.hourlyCost }}</span>
                        </td>
                        <td>
                            <input v-if="!isView" v-model="item.perKwhCost">
                            <span v-else>{{ item.perKwhCost }}</span>
                        </td>
                        <td>
                            <input v-if="!isView" v-model="item.monthlyPowerGeneration">
                            <span v-else>{{ item.monthlyPowerGeneration }}</span>
                        </td>
                        <td>
                            <input v-if="!isView" v-model="item.monthlyPowerCost">
                            <span v-else>{{ item.monthlyPowerCost }}</span>
                        </td>
                        <td>
                            <input v-if="!isView" v-model="item.remarks">
                            <span v-else>{{ item.remarks }}</span>
                        </td>
                    </tr>
                </tbody>
            </table>
        </div>
    </div>
</template>

<script>
import { savePowerCost, getPowerCostById } from '@/api/powerCost'
import html2canvas from 'html2canvas'
import jsPDF from 'jspdf'

export default {
    data() {
        return {
            powerCostList: [
                {
                    loadName: '',
                    hourlyCost: '',
                    perKwhCost: '',
                    monthlyPowerGeneration: '',
                    monthlyPowerCost: '',
                    remarks: ''
                }
            ],
            selectedIndices: [],
            isAllSelected: false,
            isView: false,
            isEdit: false
        }
    },
    created() {
        const { id, type } = this.$route.query
        if (id) {
            this.fetchData(id)
            this.isView = type === 'view'
            this.isEdit = type === 'edit'
        }
    },
    watch: {
        selectedIndices(newValue) {
            this.isAllSelected = newValue.length === this.powerCostList.length
        }
    },
    methods: {
        async fetchData(id) {
            try {
                const result = await getPowerCostById(id)
                if (result) {
                    this.powerCostList = [result.data]
                }
            } catch (error) {
                console.error('获取数据失败', error)
                this.$message.error('获取数据失败')
            }
        },
        async saveData() {
            try {
                // 数据验证
                for (const item of this.powerCostList) {
                    if (!item.loadName) {
                        this.$message.error('负荷名称不能为空')
                        return
                    }
                    if (!item.hourlyCost || isNaN(item.hourlyCost)) {
                        this.$message.error('每小时费用必须为数字')
                        return
                    }
                    if (!item.perKwhCost || isNaN(item.perKwhCost)) {
                        this.$message.error('每度电费用必须为数字')
                        return
                    }
                    if (!item.monthlyPowerGeneration || isNaN(item.monthlyPowerGeneration)) {
                        this.$message.error('每月发电度数必须为数字')
                        return
                    }
                    if (!item.monthlyPowerCost || isNaN(item.monthlyPowerCost)) {
                        this.$message.error('每月发电费用必须为数字')
                        return
                    }
                }

                const result = await savePowerCost(this.powerCostList)
                if (result) {
                    this.$message.success('保存成功')
                    this.goToList()
                }
            } catch (error) {
                console.error('保存失败', error)
                this.$message.error('保存失败')
            }
        },
        goBack() {
            this.$router.push('/main/renshi/renshizhidu')
        },
        goToList() {
            this.$router.push('/main/renshi/renshizhidu/dianfeihs/dianfeihsList')
        },
        addItem() {
            this.powerCostList.push({
                loadName: '',
                hourlyCost: '',
                perKwhCost: '',
                monthlyPowerGeneration: '',
                monthlyPowerCost: '',
                remarks: ''
            });
        },
        toggleSelectAll() {
            if (this.isAllSelected) {
                this.selectedIndices = Array.from({ length: this.powerCostList.length }, (_, i) => i);
            } else {
                this.selectedIndices = [];
            }
        },
        deleteSelected() {
            this.selectedIndices.sort((a, b) => b - a).forEach(index => {
                this.powerCostList.splice(index, 1);
            });
            this.selectedIndices = [];
            this.isAllSelected = false;
        },
        // async printToPDF() {
        //     const doc = new jsPDF('p', 'pt', 'a4');
        //     const elementList = document.querySelectorAll('#format-table');
        //     const pageHeight = 841.89;
        //     let positionY = 0;

        //     for (let i = 0; i < elementList.length; i++) {
        //         const element = elementList[i];
        //         await html2canvas(element).then((canvas) => {
        //             const imgData = canvas.toDataURL('image/png');
        //             const imgWidth = 522;
        //             const imgHeight = (canvas.height * imgWidth) / canvas.width;

        //             if (positionY + imgHeight > pageHeight) {
        //                 // 如果当前图片超出页面高度，添加新页面
        //                 doc.addPage();
        //                 positionY = 0;
        //             }

        //             doc.addImage(imgData, 'PNG', 40, positionY, imgWidth, imgHeight);
        //             positionY += imgHeight; // 添加一些间距
        //         });
        //     }

        //     doc.save('发电费用核算表.pdf');
        // }
        printForm() {
            window.print()
        },
        goBock() {
            this.$router.push('/main/renshi/renshizhidu')
        },
    }
};
</script>

<style scoped>
.button-container {
    display: flex;
    justify-content: space-between;
    padding-top: 20px;
}

#format-table {
    /* padding: 0px 20px; */
}

table {
    border-collapse: collapse;
    width: 100%;
    margin-top: 10px;
}

th,
td {
    border: 1px solid #000;
    padding: 3px;
}

input {
    border: 0px;
}

/* 
button {
    padding: 5px 10px;
    margin: 10px 10px;
} */
@media print {

    body,
    html {
        margin: 0;
        padding: 0;
    }

    .el-button {
        display: none !important;
    }

    .checkbox {
        display: none;
    }

    .leave-adjustment-form {
        margin: 0;
        padding: 0;
        page-break-inside: avoid;
    }

    table {
        page-break-inside: avoid;
        border-collapse: collapse;
        box-shadow: none;
        width: 95%;
    }

    table th,
    table td {
        border: 1px solid #000;
        padding: 10px 0px;
        white-space: nowrap !important;
    }

    input,
    textarea {
        border: none !important;
        background-color: transparent !important;
        text-align: center;
        resize: none;
    }

    .instructions {
        page-break-before: avoid;
    }
}
</style>